package com.atom.app.mvvm.ui.activities

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.LayoutMode
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.bottomsheets.BottomSheet
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.afollestad.materialdialogs.list.customListAdapter
import com.atom.app.mvvm.AppModel
import com.atom.app.mvvm.BR
import com.atom.app.mvvm.R
import com.atom.app.mvvm.VMFactory
import com.atom.app.mvvm.abase.BaseKingActivity
import com.atom.app.mvvm.abase.BaseKingViewModel
import com.atom.app.mvvm.Contacts
import com.atom.app.mvvm.databinding.ActivityTaskDetailBinding
import com.atom.app.mvvm.net.BaseResponse
import com.atom.app.mvvm.net.bean.TaskDetail
import com.atom.app.mvvm.utils.*
import com.atom.module.logger.Logger
import com.atom.module.mvvm.livedata.SingleLiveData
import com.atom.module.mvvm.util.*
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.squareup.picasso.Picasso
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver
import io.reactivex.rxjava3.schedulers.Schedulers

class TaskDetailActivity : BaseKingActivity<ActivityTaskDetailBinding, TaskDetailViewModel>() {

    private var taskId: Int? = null

    override fun initArgs(intent: Intent, savedInstanceState: Bundle?): Boolean {
        val longExtra = intent.getIntExtra(Contacts.tag_task_id, -1)
        if (longExtra < 0) {
            return false
        }
        taskId = longExtra

        Auto.registerTask(this::class) {
            viewModel.getTaskDetail(taskId)
            true
        }
        return super.initArgs(intent, savedInstanceState)
    }

    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_task_detail
    }

    override fun initViewModel(): TaskDetailViewModel {
        return ViewModelProvider(this, VMFactory).get(TaskDetailViewModel::class.java)
    }

    override fun initViewBinding(
        binding: ActivityTaskDetailBinding,
        viewModel: TaskDetailViewModel
    ) {
        super.initViewBinding(binding, viewModel)
        viewModel.dataUpdate.observe(this) { taskDetail ->
            binding.tdTitle.setText("${taskDetail.taskName}")
            binding.tdDateValue.setText("${taskDetail.date}")
            binding.tdTimeValue.setText("${taskDetail.time}")
            binding.tdOutletsValue.setText("${taskDetail.branchName}")
            var fenshu = 0.0
            val filter = taskDetail.topicDetail?.filter {
                Logger.e(JacksonUtils.objectMapper.writeValueAsString(it))
                if (it.fields?.parentId == 0 && it.fields?.isEndNode == false) {
                    it.fields?.resultScore?.also { score ->
                        fenshu += score
                    }
                    true
                } else {
                    false
                }
            } ?: return@observe
            binding.tdAchievementValue.setText("${fenshu}")
            viewModel.adapter.replaceAll(filter)
        }

        viewModel.finishRefreshEvent.observe(this) {
            binding.taskDetailUpdate.finishRefresh()
        }

        viewModel.showItem.observe(this) {
            it.fields?.quesId?.also { parent ->
                viewModel.dataUpdate.value?.also { data ->
                    val filter = data.topicDetail?.filter { entry ->
                        entry.fields?.parentId == parent
                    }
                    if (filter == null || filter.isEmpty()) {
                        return@observe
                    } else {
                        viewModel.itemAdapter.replaceAll(filter)
                        MaterialDialog(this, BottomSheet(LayoutMode.WRAP_CONTENT)).show {
                            customListAdapter(viewModel.itemAdapter)
                            lifecycleOwner(this@TaskDetailActivity)
                        }
                    }
                }
            }
        }
        // 布局刷新
        binding.taskDetailUpdate.setRefreshHeader(ClassicsHeader(this))
        binding.taskDetailUpdate.setRefreshFooter(ClassicsFooter(this))
        binding.taskDetailUpdate.setEnableRefresh(true)
        binding.taskDetailUpdate.setEnableLoadMore(true)
        binding.taskDetailUpdate.setOnRefreshListener {
            viewModel.getTaskDetail(taskId)
        }
        binding.taskDetailUpdate.setOnLoadMoreListener { refreshlayout ->
            toastShow("敬请期待")
        }
        // binding.taskUpdate.autoRefresh()
        binding.taskDetailItemList.layoutManager = LinearLayoutManager(this)
        binding.taskDetailItemList.adapter = viewModel.adapter
    }

    override fun initVariableId(): Int {
        return BR._all
    }

    override fun initData(view: View) {
        super.initData(view)
        if (!Auto.startTask(this)) {
            viewModel.getTaskDetail(taskId)
        }
    }
}


class TaskDetailViewModel : BaseKingViewModel<AppModel>(AppModel) {

    val dataUpdate = SingleLiveData<TaskDetail.Data>()

    var finishRefreshEvent: SingleLiveData<Unit> = SingleLiveData()

    val showItem = SingleLiveData<TaskDetail.TopicDetail>()

    val adapter = object : AbstractAdapter<TaskDetail.TopicDetail>(object :
        AdapterListener<TaskDetail.TopicDetail> {
        override fun onItemClick(
            view: View,
            adapter: AbstractAdapter<TaskDetail.TopicDetail>,
            viewHolder: AbstractViewHolder<TaskDetail.TopicDetail>,
            data: TaskDetail.TopicDetail
        ) {
            super.onItemClick(view, adapter, viewHolder, data)
            showItem.setValue(data)
        }
    }) {
        override fun getItemViewType(position: Int, data: TaskDetail.TopicDetail): Int {
            return R.layout.item_task_detail
        }

        override fun onCreateViewHolder(
            contentView: View,
            viewType: Int
        ): AbstractViewHolder<TaskDetail.TopicDetail> {
            return ViewHolder(contentView)
        }
    }

    inner class ViewHolder(v: View) : AbstractViewHolder<TaskDetail.TopicDetail>(v) {

        override fun onBind(data: TaskDetail.TopicDetail) {
            view(R.id.quesName, { t: TextView ->
                t.text =
                    "${data.fields?.quesName}(满分:${data.fields?.totalScore})|得分${data.fields?.resultScore}"
            })
        }

    }

    val itemAdapter = object : AbstractAdapter<TaskDetail.TopicDetail>(object :
        AdapterListener<TaskDetail.TopicDetail> {
        override fun onItemClick(
            view: View,
            adapter: AbstractAdapter<TaskDetail.TopicDetail>,
            viewHolder: AbstractViewHolder<TaskDetail.TopicDetail>,
            data: TaskDetail.TopicDetail
        ) {
            super.onItemClick(view, adapter, viewHolder, data)
        }
    }) {
        override fun getItemViewType(position: Int, data: TaskDetail.TopicDetail): Int {
            return R.layout.item_task_entry_detail
        }

        override fun onCreateViewHolder(
            contentView: View,
            viewType: Int
        ): AbstractViewHolder<TaskDetail.TopicDetail> {
            return EntryViewHolder(contentView)
        }
    }

    inner class EntryViewHolder(v: View) : AbstractViewHolder<TaskDetail.TopicDetail>(v) {

        override fun onBind(data: TaskDetail.TopicDetail) {
            view(R.id.quesName) { t: TextView ->
                t.text =
                    "${data.fields?.quesName}(满分:${data.fields?.totalScore})|得分${data.fields?.resultScore}"
            }
            view(R.id.quesDetail) { t: TextView ->
                t.text = data.fields?.quesDetail
            }
            view(R.id.quesImage) { t: ImageView ->
                val path = data.fields?.deductionReasonImage
                if (path.isNullOrEmpty()) {
                    t.setImageDrawable(t.resources.getDrawable(R.drawable.icon_good_job))
                } else {
                    Picasso.get().load(path).into(t)
                }
            }
        }
    }

    fun getTaskDetail(taskId: Int?) {
        addSubscribe(
            model.netApi.getTaskDetail(taskId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(object : BlockingBaseObserver<BaseResponse<TaskDetail.Data>>() {
                    override fun onNext(t: BaseResponse<TaskDetail.Data>) {
                        t.data?.also {
                            dataUpdate.setValue(it)
                        }
                        finishRefreshEvent.setValue(Unit)
                    }

                    override fun onError(e: Throwable) {
                        Logger.e(e)
                        finishRefreshEvent.setValue(Unit)
                    }
                })
        )
    }

}
